package com.hyc.DataStructure.Stack;

/**
 * @projectName: DataStructure
 * @package: com.hyc.DataStructure.Stack
 * @className: ListStackDemo
 * @author: 冷环渊 doomwatcher
 * @description: TODO 用链表来模拟栈
 * @date: 2021/12/23 18:23
 * @version: 1.0
 */
public class ListStackDemo {
    public static void main(String[] args) {
        listStack listStack = new listStack();
        listStack.push(5);
        listStack.push(6);
        listStack.push(9);
        System.out.println("出栈前");
        listStack.list();
        System.out.println("出栈后");
        System.out.println("出栈：" + listStack.pop());
        System.out.println("出栈：" + listStack.pop());
        listStack.list();

    }

}

class listStack {
    //创建一个头结点
    StackNode head = new StackNode(0);
    StackNode temp = head;

    //判断是否为空
    public boolean isempty() {
        return head.next == null;
    }

    //压入栈
    public void push(int value) {
        //创建节点对象
        StackNode newnode = new StackNode(value);
        //改变头节点指针的指向
        temp.next = newnode;
        //指针后移
        temp = temp.next;
    }

    //出栈
    public int pop() {
        if (isempty()) {
            throw new RuntimeException("栈空");
        }
        StackNode Before = head;
        //将 before 节点遍历到 temp也就是最后一个节点的上一个节点，让temp指针想前遍历
        while (true) {
            if (Before.next == temp) {
                break;
            }
            Before = Before.next;
        }
        //将before的下一个节点为空相当于出栈之后 删除引用
        Before.next = null;
        //取值
        int value = temp.data;
        //此时 before指向的这个节点就是上一个节点的位置，将temp前移动，重复操作实现出栈
        temp = Before;
        return value;
    }

    //遍历栈
    public void list() {
        //    判断非空
        if (isempty()) {
            System.out.println("栈是空的");
            return;
        }
        StackNode temp = head;
        while (true) {
            if (temp.next == null) {
                break;
            }
            System.out.println(temp.next.data);
            temp = temp.next;
        }
    }
}

//单向链表节点
class StackNode {
    // 数据
    public int data;
    //下一个节点
    public StackNode next;

    public StackNode(int data) {
        this.data = data;
    }

    //方便输出语句输出
    @Override
    public String toString() {
        return "StackNode{" +
                ", data='" + data + '\'' +
                ", next=" + next +
                '}';
    }
}